import { defineStore } from "pinia";
import storage from "@/utils/storage";
import { AppConsts } from "@/models/AppConsts";
import { LoginResultVo } from "@/models/userinfo/LoginResultVo";


export const useUserStore = defineStore("user-store", {
    state: () => ({
        userInfo: {} as LoginResultVo | null,
        tkn: "" as string
    }),
    getters: {
        getUserInfo: (state): LoginResultVo | null => {
            if (state.userInfo?.id) return state.userInfo;
            else return storage.getStorage(AppConsts.USER_INFO);
        },
        token: (state): string => {
            if (state.tkn) return state.tkn;
            return storage.getStorage(AppConsts.USER_TKN);
        }
    },
    actions: {
        setUserInfo(userInfo: LoginResultVo) {
            this.userInfo = userInfo;
            this.tkn = userInfo.token;

            storage.setStorage(AppConsts.USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000);
            storage.setStorage(AppConsts.USER_TKN, userInfo.token, 7 * 24 * 60 * 60 * 1000);
        },
    },
});